class Solution {
public:
    int bfs(vector<vector<int>>& grid)
    {
        int dx[] = { 1, 0, -1, 0 }, dy[] = { 0, 1, 0, -1 };
        int minutes = 0;

        queue<pair<int, int>> q;
        for (int i = 0; i < grid.size(); ++i)
        {
            for (int j = 0; j < grid[0].size(); ++j)
            {
                if (grid[i][j] == 2)
                {
                    q.push({ i, j });
                }
            }
        }

        while (q.size())
        {
            bool flag = false;
            int n = q.size();
            while (n--)
            {
                auto [x, y] = q.front(); q.pop();
                for (int t = 0; t < 4; ++t)
                {
                    int a = dx[t] + x, b = dy[t] + y;
                    if (a >= 0 && a < grid.size() && b >= 0 && b < grid[0].size() && grid[a][b] == 1)
                    {
                        q.push({ a, b });
                        grid[a][b] = 2;
                        flag = true;
                    }
                }
            }
            if (flag) ++minutes;
        }

        for (int i = 0; i < grid.size(); ++i)
        {
            for (int j = 0; j < grid[0].size(); ++j)
            {
                if (grid[i][j] == 1)
                {
                    return -1;
                }
            }
        }

        return minutes;
    }
    int orangesRotting(vector<vector<int>>& grid) {
        return bfs(grid);
    }
};